package com.sxkiler.demo.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.sxkiler.demo.utils.SpringContextUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * mq发送工具类
 */
public class RocketMqProducerUtil {
    private static final Logger logger = LoggerFactory.getLogger(RocketMqProducerUtil.class);

    /**
     * 发送处理消息
     * @param topic
     * @param adaptor
     * @param param
     * @param delayLevel
     * @throws Exception
     */
    public static String sendSimpleMessage(String topic, String adaptor, Map param, int delayLevel) {
        DefaultMQProducer defaultMQProducer = SpringContextUtil.getBean("defaultMQProducer");
        return sendSimpleMessage(defaultMQProducer,topic,adaptor,param,delayLevel);
    }
    public static String sendSimpleMessage(DefaultMQProducer defaultMQProducer,String topic, String adaptor, Map param, int delayLevel) {
        try{
            if(param==null){
                param = new HashMap();
            }
            //添加对发送charge消息的适配
            if(StrUtil.isEmpty((String)(param.get("adaptor")))){
                param.put("adaptor",adaptor);
            }else{
                adaptor = (String)param.get("adaptor");
            }
            Message msg = new Message(topic,adaptor, JSONObject.toJSONBytes(param));
            //消息延迟级别
            msg.setDelayTimeLevel(delayLevel);
            //存放MDC数据
            SendResult sendResult = defaultMQProducer.send(msg);
            logger.info("RocketMQ发送消息,topic={},adaptor={},msgId={},param={}",topic,adaptor,sendResult.getMsgId(),param);
            return sendResult.getMsgId();
        }catch(Exception e){
            logger.error("rocketmq发送消息异常："+e.getMessage(),e);
        }
        return null;
    }
}
